#!/usr/bin/env python
import os
import jinja2
import logging

from google.appengine.api import users

from modules.box import Box
from modules.box import Stuff
from modules.box import Stuff

from modules.contact import Contact as Con
from modules.Predef import Predef as PRE
from modules.parser import parser as ROCK

class Cell:
        
    ####################################################
    # Initialize
    ####################################################
    def __init__(self,context):
        self.context=context
        self.message=''
        self.errmessage=''

        la=self.context.request.get('label')

        if la != '':
            self.b = Box.getBox(la)
            if not self.b:
                self.b = Box(label=la) 
                self.b.stuffs = []
                self.MESSAGE("Creating a new box...")
        else:
            self.ERRMESSAGE("IMPOSSIBLE!!!Empty box!!!")


    ####################################################
    # For message
    ####################################################
    def MESSAGE(self,m):
        self.message=PRE.genMessage(self.message,m)

    def ERRMESSAGE(self,m):
        self.errmessage=PRE.genMessage(self.errmessage,"ERROR:"+m)

    ####################################################
    # Show the content
    ####################################################
    def getContent(self, t):

        st_new=Stuff( pattern='', message=self.context.request.get('message'),
                expression=self.context.request.get('lambda') , p1=self.context.request.get('p1'),
                    p2=self.context.request.get('p2'))

        temp_path=os.path.join(
                os.path.dirname(__file__),
                "../templates/")

        temp=jinja2.Environment(loader=jinja2.FileSystemLoader(temp_path)).get_template(t)

        user = users.get_current_user()
        if user:
            Con.addUser(user.email())
            u = '%s <a href="%s"> sign out </a>' % (user.nickname(), users.create_logout_url("/"))
        else:
            u = 'guest'
        return temp.render(
                {
                    'doors':PRE.doors,
                    'user': u,
                    'b':self.b,
                    'e':self.errmessage,
                    'm':self.message,
                    'n':st_new,
                    })

    ####################################################
    # Read and Check settings to GET
    ####################################################
    def doGet(self):
        self.context.response.out.write(self.getContent('editsetting.html'))

    ####################################################
    # Read and Check settings to POST
    ####################################################
    def doPost(self):

        self.b.url=self.context.request.get('url')
        self.b.description=self.context.request.get('des')

        #elif not self.b.setTo(self.request.get('mailto'),self.request.get('topic')):
        #    self.ERRMESSAGE('Invalid Email address!')

        # update the current settings
        for k in self.b.stuffs:
            # check deleted item
            if self.context.request.get('hidden_'+k.ID()) == 'Deleted':
                self.b.stuffs.remove(k)
                #logging.info("<{}> has been deleted!".format(k) )
                self.MESSAGE('Success: <{}> has been deleted!'.format(k.ID()))
            # check update item
            else:
                k.pattern=self.context.request.get('pattern_'+k.ID())
                k.message=self.context.request.get('message_'+k.ID())
                k.expression=self.context.request.get('lambda_'+k.ID())
                k.p1=self.context.request.get('p1_'+k.ID())
                k.p2=self.context.request.get('p2_'+k.ID())

        # add a new item
        if self.context.request.get('pattern')!='':
            st=Stuff( pattern=self.context.request.get('pattern'), message=self.context.request.get('message'),
                expression=self.context.request.get('lambda') , p1=self.context.request.get('p1'),
                    p2=self.context.request.get('p2'))

            self.b.stuffs.append(st)

        self.MESSAGE('Success: The new data has been updated!')
        ROCK(self.b).run()
        self.MESSAGE('Report:{}'.format(self.b.report(isHTML=True)))

        if self.context.request.get('Update'):
            self.b.put()
            self.context.response.out.write(self.getContent('editsetting.html'))
        else:
            if self.b.isRunning:
                self.b.drawbackIt()
            else:
                self.b.lauchIt()
            self.context.redirect('/')
